package com.gemme.gemme.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.gemme.gemme.MainActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.login.BindInputTelActivity;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.MsgActivity;
import com.gemme.gemme.login.UseInfoBean;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.test.TestActivity;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class LoginView extends RelativeLayout implements View.OnClickListener {
    private Context context;
    private OnLoginClick onLoginClick;

    public LoginView(Context context) {
        this(context,null);
    }

    public LoginView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LoginView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initView();
    }
    EditText acount;
    ImageView iv_weixin;
    String weixin_accessToken;
    String weixin_openid;
    private void initView() {
       LayoutInflater.from(context).inflate(R.layout.view_login,this);
        GeButton gebt= findViewById(R.id.gebt);
        acount = findViewById(R.id.acount);
        iv_weixin = findViewById(R.id.iv_weixin);
        gebt.findViewById(R.id.button1).setOnClickListener(this);
        if (!(context instanceof Activity)){
           return;
        }
        findViewById(R.id.des1).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, TestActivity.class));
            }
        });

        findViewById(R.id.iv_weixin).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                //获取微信授权
                UMShareAPI.get(context).getPlatformInfo((Activity)context, SHARE_MEDIA.WEIXIN, new UMAuthListener(){

                    @Override
                    public void onStart(SHARE_MEDIA share_media) {

                    }

                    @Override
                    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                        System.out.println("");
                        System.out.println("");
//                        et_accessToken.setText();
                        weixin_accessToken = map.get("accessToken") + "";
                        weixin_openid = map.get("openid") + "";
                        System.out.println("");


                        isbindingmobile();
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                        System.out.println("");
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media, int i) {

                    }
                });
            }
        });
    }
//检测微信号是否存在
    private void isbindingmobile() {
        if(TextUtils.isEmpty(weixin_openid))
            return;
        //http://192.168.1.6:9999/user/userapp/isbindingmobile?openId=35_-NVQprUOyqmdeyoGa8CR-uE4TEneDd5rCYwt6vSvbtjc5Dp5ZjlFvHIlvjiYD1ToE4qbKy18Fdyo4t5CWrx_g5X-K2tOrG7RPPG1S6T2ulQ
        String url = DataManager.BaseUrl + "user/userapp/isbindingmobile?" +
                "openId=" + weixin_openid;
                ;
        HashMap<String, String> headMap = new HashMap<>();
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
               try{
                   JSONObject jsonObject = new JSONObject(response);
                   boolean isbindingmobile = jsonObject.getBoolean("data");
                   System.out.println("");

                   if(isbindingmobile){//已绑定获取用户信息
                       toWeixinLogin();
                   }else{//未绑定去验证码注册
                       Intent intent = new Intent(context, BindInputTelActivity.class);
                       intent.putExtra("weixin_openid",weixin_openid);
                       intent.putExtra("weixin_accessToken",weixin_accessToken);
                       intent.putExtra(MsgActivity.TYPE,MsgActivity.type_weixin);
                       context.startActivity(intent);
                   }
               }catch (Exception e){

               }
            }
        });
    }

    //检测手机号是否存在
    private void isbindingmobileExist() {
        String account = acount.getText() + "";
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context,"手机号不能为空",Toast.LENGTH_SHORT);
            return;
        }
        if(TextUtils.isEmpty(account))
            return;
        //http://192.168.1.6:9999/user/userapp/isbindingmobile?openId=35_-NVQprUOyqmdeyoGa8CR-uE4TEneDd5rCYwt6vSvbtjc5Dp5ZjlFvHIlvjiYD1ToE4qbKy18Fdyo4t5CWrx_g5X-K2tOrG7RPPG1S6T2ulQ
        String url = DataManager.BaseUrl + "user/userapp/isbindingmobile?" +
                "openId=" + account;
        ;
        HashMap<String, String> headMap = new HashMap<>();
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", null, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    JSONObject jsonObject = new JSONObject(response);
                    boolean isbindingmobile = jsonObject.getBoolean("data");
                    System.out.println("");

                    if(isbindingmobile){//已绑定获取用户信息
                        //有账号流程
                        Intent intent = new Intent(context, MsgActivity.class);
                        intent.putExtra("account",account);
                        intent.putExtra(MsgActivity.TYPE,MsgActivity.type_tel);
                        context.startActivity(intent);
                    }else{//未注册,填写手机号,邀请码
                        Intent intent = new Intent(context, BindInputTelActivity.class);
                        intent.putExtra("weixin_openid",weixin_openid);
                        intent.putExtra("weixin_accessToken",weixin_accessToken);
                        intent.putExtra("account",account);
                        intent.putExtra(MsgActivity.TYPE,MsgActivity.type_tel);
                        context.startActivity(intent);
                    }
                }catch (Exception e){

                }
            }
        });
    }


    private void toWeixinLogin() {


        if(TextUtils.isEmpty(weixin_openid) || TextUtils.isEmpty(weixin_accessToken)){
            Toast.makeText(context, "缺少数据", Toast.LENGTH_SHORT).show();
            return;
        }


        String url = DataManager.BaseUrl + "auth/mobile/token/social?" +
                "phone=WX@" + weixin_openid
                +"&grant_type=" + "mobile"
                +"&access_token=" + ""
                +"&telephone=" + ""

                ;
        ;
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put("Authorization","Basic bW9iaWxlOm1vYmlsZQ==");
        DataManager.toServer3(context, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    UseInfoBean useInfos = JSON.parseObject(response,UseInfoBean.class);
                    SharedPreferences MSP = context.getSharedPreferences(Constant.MSP, Context.MODE_PRIVATE);
                /*   Constant.ACCESS_TOKEN = useInfos.getAccess_token();+
                   Constant.REFRESH_TOKEN = useInfos.getRefresh_token();
                   Constant.ACCESS_TOKENTIME = System.currentTimeMillis();
                   Constant.REFRESH_TIME = System.currentTimeMillis();*/
                    MSP.edit().putString(Constant.ACCESS_TOKEN, useInfos.getAccess_token()).apply();
                    MSP.edit().putString(Constant.REFRESH_TOKEN, useInfos.getRefresh_token()).apply();
                    MSP.edit().putString(Constant.UserId, useInfos.getUser_info().getId() + "").apply();
                    MSP.edit().putString(Constant.ACCESS_TOKENTIME, System.currentTimeMillis() + "").apply();
                    MSP.edit().putString(Constant.REFRESH_TIME, System.currentTimeMillis() + "").apply();

                    context.startActivity(new Intent(context, MainActivity.class));
                    if(context instanceof Activity){
                        ((Activity)context).finish();
                    }

                }catch (Exception e){

                }
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.button1:
                login();
                break;
        }
    }

    private void login() {
        String account = acount.getText() + "";
        if(TextUtils.isEmpty(account)){
            Toast.makeText(context,"手机号不能为空",Toast.LENGTH_SHORT);
            return;
        }

       /* if(onLoginClick != null)
            onLoginClick.onLoginClick();*/

//                getData();
        isbindingmobileExist();

    }

    public void setOnLoginClick(OnLoginClick onLoginClick){

        this.onLoginClick = onLoginClick;
    }
    public interface OnLoginClick{
        void onLoginClick();
    }

    public String getAccount(){
        return  acount.getText() + "";
    }
}
